package com.example.treeHole.service.impl;

import com.example.treeHole.dao.SensitiveWordsMapper;
import com.example.treeHole.service.SensitiveWordService;
import com.example.treeHole.utils.BaseContext;
import com.example.treeHole.utils.TrieNode;
import com.example.treeHole.utils.TrieTree;
import com.example.treeHole.utils.Uuid;
import com.example.treeHole.vo.SensitiveWords;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.PostConstruct;
import java.util.Date;
import java.util.List;

@Service
public class SensitiveWordServiceImpl implements SensitiveWordService {
    private TrieTree trieTree = new TrieTree();

    @Autowired
    private SensitiveWordsMapper sensitiveWordsMapper;

    @PostConstruct
    public void initTrieTree() {
       List<SensitiveWords> words=sensitiveWordsMapper.findAll();
       words.forEach(sw->trieTree.addWord(sw.getSensitiveWord()));
    }
    @Override
    public void addSensitiveWords(String word) {
        int i = sensitiveWordsMapper.existsByWord(word);
        if (i == 0) {
            throw new RuntimeException("敏感词已经存在");
        }
        SensitiveWords newWord = new SensitiveWords();
        newWord.setSensitiveWord(word);
        newWord.setId(Uuid.getUuID());
        newWord.setCreateBy(BaseContext.getCurrentId());
        newWord.setCreateDate(new Date());
        sensitiveWordsMapper.insert(newWord);
        trieTree.addWord(word);
    }

    @Override
    public String filterText(String text) {
        return trieTree.filter(text);
    }
}
